const { Service } = require("egg");
const fs = require("fs");
const { parse } = require("path");

class BookService extends Service {
    //添加书籍
    async addBook(body) {
            try {
                const book = {
                    title: body.title,
                    orderby: body.orderby,
                    img: body.img
                }
                await this.app.model.Book.create(book)
                return true
            } catch (error) {
                return false
            }
        }
        //获取书籍
    async getBook(query) {
            try {
                const number = parseInt(query.page)
                const start = number * 10 - 10
                    const total = parseInt(query.total)
                    const bookList = await this.app.model.Book.findAll({
                        limit:[start,total],
                        order: [
                            ["orderby", "desc"]
                        ]
                    })
                    return bookList
            } catch (error) {
                return null
            }
        }
        //删除书籍
    async deleteBook(id) {
            try {
               let chapterList = await this.app.model.Chapter.findAll({
                    where:{
                        book_id:id
                    }
                })
                for(let chapter of chapterList){
                    await this.app.model.Section.destroy({
                        where: {
                            chapter_id:chapter.id
                        }
                    })
                }
                await this.app.model.Chapter.destroy({
                    where: {
                        book_id:id
                    }
                })
                await this.app.model.Book.destroy({
                    where: {
                        id
                    }
                })
                return true
            } catch (error) {
                return false
            }
        }
        //更新书籍
    async updateBook(id, book) {
        try {
            const newBook = {
                title: book.title,
                img: book.img,
                orderby: book.orderby
            }
            let u = await this.app.model.Book.update(newBook, {
                where: {
                    id
                }
            })
            return u
        } catch (error) {
            return false
        }
    }
}

module.exports = BookService